from infoUi import wx,os
from adiffUi import myAdiffUi
from comUi import myComUi
from netUi import myNetUi
from otaStateMachine import myStateMachine

class otaUi(myAdiffUi,myComUi,myNetUi,myStateMachine):
    def __init__(self, parent=None, title="MyTest",pos = (1000,680),size = (900,700)):
        wx.Frame.__init__(self,parent=parent, title=title,size=size)
        #设置背景颜色
        #self.SetBackgroundColour(wx.Colour(255,255,255))
        self.panel = wx.Panel(self,size = (900,700))

    def setUpOtaBtnUi(self):
        self.otaUiCtr = {
            'BoxSizer':'',
            'up':'',
            'down':'',
            'all':'',
            'reset':'',
        }
        otaBox_label = wx.StaticBox(self.panel, -1, "ota")
        self.otaUiCtr['BoxSizer'] = wx.StaticBoxSizer(otaBox_label,wx.VERTICAL)
        otaBnt_box = wx.BoxSizer(wx.HORIZONTAL)
        config_box = wx.BoxSizer(wx.HORIZONTAL)

        #按钮
        self.otaUiCtr['up'] = wx.Button(self.panel,label = "升级")
        self.otaUiCtr['down'] = wx.Button(self.panel,label = "降级")
        self.otaUiCtr['all'] = wx.Button(self.panel,label = "ALL")
        self.otaUiCtr['reset'] = wx.Button(self.panel,label = "Rest")

        #选项框
        netList = ['ftp', 'http']
        self.__rbox1 = wx.RadioBox(self.panel, label = 'net', choices = netList,majorDimension = 1, style = wx.RA_SPECIFY_ROWS)

        #布局
        otaBnt_box.Add(self.otaUiCtr['up'],proportion = 1,flag=wx.EXPAND|wx.ALL,border = 3)
        otaBnt_box.Add(self.otaUiCtr['down'],proportion = 1,flag=wx.EXPAND|wx.ALL,border = 3)
        otaBnt_box.Add(self.otaUiCtr['all'],proportion = 1,flag=wx.EXPAND|wx.ALL,border = 3)

        config_box.Add(self.__rbox1,proportion = 1,flag=wx.EXPAND)

        self.otaUiCtr['BoxSizer'].Add(config_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        self.otaUiCtr['BoxSizer'].Add((-1,10))
        self.otaUiCtr['BoxSizer'].Add(otaBnt_box,proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        self.otaUiCtr['BoxSizer'].Add(self.otaUiCtr['reset'],proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)

        #绑定事件
        self.otaUiCtr['up'].Bind(wx.EVT_BUTTON, self.onUpBnt)
        self.otaUiCtr['down'].Bind(wx.EVT_BUTTON, self.onDownBnt)
        self.otaUiCtr['all'].Bind(wx.EVT_BUTTON, self.onAllBnt)
        self.otaUiCtr['reset'].Bind(wx.EVT_BUTTON, self.onResetBnt)
        self.__rbox1.Bind(wx.EVT_RADIOBOX,self.onRadioBox1)

    def configInit(self):
        #获取配置文件
        config = os.path.join(os.getcwd(),"config.json")
        if(os.path.isfile(config)):
            tmp = self.getConf()
            #更新ftpConfig
            self.netConfig[0] = tmp['conf']['ftpConf']
            self.netConfig[0]['localPath'] = os.path.join(os.getcwd(),"out")
            #更新sftpConf
            self.netConfig[1] = tmp['conf']['sftpConf']
            self.netConfig[1]['localPath'] = os.path.join(os.getcwd(),"out")
            #更新statusMacConfig
            self.stateMacConf = tmp['conf']['statusTimeOut']
            #更新adiffConfig
            self.adiffConfig = tmp['conf']['adiffPkgName']
            self.otaCmdConf = tmp['conf']['otaCmdConf']

        else:
            self.tmpConf['conf']['statusTimeOut'] = self.stateMacConf
            self.tmpConf['conf']['otaCmdConf'] = self.otaCmdConf
            self.saveConf(self.tmpConf)
            pass
    def saveConfig(self,evt):
        try:
            self.closeSerial()
            config = os.path.join(os.getcwd(),"config.json")
            if(os.path.isfile(config)):
                tmp = self.getConf()
                #保存ftpConfig
                tmp['conf']['ftpConf'] = self.netConfig[0]
                #保存sftpConfig
                tmp['conf']['sftpConf'] = self.netConfig[1]
                #保存statusMacConfig
                tmp['conf']['statusTimeOut'] = self.stateMacConf
                #保存adiffConfig
                tmp['conf']['adiffPkgName'] = self.adiffConfig
                self.saveConf(tmp)
            else:
                pass
            wx.Exit()
        except Exception as err:
            print('ERROR:%s ' % err)
            wx.Exit()

    def setUpMainUi(self):
        self.setUpInfoUi()
        self.configInit()
        self.setUpOtaBtnUi()
        self.setUpAdiffUi()
        self.setUpNetUi()
        self.setUpComUi()
        self.setUpStatusBar()

        self.Bind(wx.EVT_CLOSE, self.saveConfig)

        vbox = wx.BoxSizer(wx.VERTICAL)
        mainUiBox = wx.BoxSizer(wx.VERTICAL)
        fgsBox = wx.FlexGridSizer(2, 2, 3, 3)

        vbox.Add(self.adiffUiCtr['BoxSizer'], proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)
        vbox.Add(self.netUiCtr['BoxSizer'], proportion = 0,flag=wx.EXPAND|wx.ALL,border = 3)

        fgsBox.AddMany([(self.infoUiCtr['BoxSizer'], 3, wx.EXPAND), \
                     (vbox, 1, wx.EXPAND),                       \
                     (self.comUiCtr['BoxSizer'], 1, wx.EXPAND),  \
                     (self.otaUiCtr['BoxSizer'], 1, wx.EXPAND)])
        fgsBox.AddGrowableCol(0, 1)
        fgsBox.AddGrowableRow(0, 1)
        mainUiBox.Add(fgsBox, proportion = 1,flag=wx.EXPAND)
        mainUiBox.Add(self.uiStatusBar['BoxSizer'], proportion = 0,flag=wx.EXPAND)
        self.panel.SetSizer(mainUiBox)
        self.statusGaugeHide()

    def onRadioBox1(self,evt):
        obj = evt.GetEventObject()
        self.otaConfig['netMode'] = str(obj.GetStringSelection())
        print('%s is clicked from Radio Box1' %(obj.GetStringSelection()))

    def onUpBnt(self,evt):
        if(self.state == 'otaIdle'):
            if(self.ser.is_open):
                #更改状态机
                self.otaConfig['testMode']='up'
                self.otaConfig['curStatus']= ''
                try:
                    self.otaPrepare()
                except Exception as e:
                    print("onUpBnt:%s " %(e))
            else:
                self.errorDebug("com not open!\r\n")
        else:
            self.errorDebug('state machine is not Idle\r\n')

    def onDownBnt(self,evt):
        if(self.state == 'otaIdle'):
            if(self.ser.is_open):
                #更改状态机
                self.otaConfig['testMode']='down'
                self.otaConfig['curStatus']= ''
                try:
                    self.otaPrepare()
                except Exception as e:
                    print("onDownBnt:%s " %(e))
            else:
                self.errorDebug("com not open!\r\n")
        else:
            self.errorDebug('state machine is not Idle\r\n')
        pass

    def onAllBnt(self,evt):
        if(self.state == 'otaIdle'):
            if(self.ser.is_open):
                #更改状态机
                self.otaConfig['testMode']='all'
                self.otaConfig['curStatus']=self.__rbox1.GetStringSelection()+'-up'
                print(self.otaConfig['curStatus'])
                try:
                    self.otaPrepare()
                except Exception as e:
                    print("onAllBnt:%s " %(e))
            else:
                self.errorDebug("com not open!\r\n")
        else:
            self.errorDebug('state machine is not Idle\r\n')
        pass

    def onResetBnt(self,evt):
        self.otaRest()


# ota Main UI demo
if __name__ == '__main__':
    app = wx.App()
    frame = otaUi(title="While there is life,there is hope.")
    frame.setUpMainUi()
    frame.Centre()
    frame.Show()
    app.MainLoop()

